package com.tie.catalogo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity {

	private Button bAceptar, bLogIn;
	private TextView txtId;
	private String esEmpleado;
	private boolean login;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		getActionBar().hide();

		inicializarVariables();
	}

	//Instancia los objetos y crea los listeners
	private void inicializarVariables() {
		// TODO Auto-generated method stub
		login = false;
		bAceptar = (Button) findViewById(R.id.bOK);
		bAceptar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (login) {
					if (txtId.getText().toString().equalsIgnoreCase("")) {
						Toast.makeText(
								getApplicationContext(),
								getResources().getString(R.string.introducirID),
								Toast.LENGTH_LONG).show();
					} else {
						comprobarID(txtId.getText().toString());
					}
				} else {
					if (txtId.getText().toString().equalsIgnoreCase("")) {
						Toast.makeText(
								getApplicationContext(),
								getResources().getString(R.string.introducirID),
								Toast.LENGTH_LONG).show();
					} else {

						if (compararID()) {
							Intent i = new Intent(Login.this,
									CatalogSelector.class);
							startActivity(i);
						} else {
							txtId.setText("");
							Toast.makeText(getApplicationContext(),
									getResources().getString(R.string.dniCoincidir), Toast.LENGTH_LONG)
									.show();
						}

					}
				}

			}
		});
		bLogIn = (Button) findViewById(R.id.bCambiarEmpl);
		bLogIn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (networkAvailable()) {
					login = true;
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.enterdni),
							Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.nonetwork),
							Toast.LENGTH_LONG).show();
				}

			}
		});

		txtId = (EditText) findViewById(R.id.txtID);
	}

	//Comprueba via internet si el DNI es correcto
	private void comprobarID(final String id) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if (esEmpleado.equalsIgnoreCase("1")) {
					Toast.makeText(getApplicationContext(), getResources().getString(R.string.ok),
							Toast.LENGTH_LONG).show();
					guardarID();
					login = false;
					Intent i = new Intent(Login.this, CatalogSelector.class);
					startActivity(i);
				} else {
					txtId.setText("");
					Toast.makeText(getApplicationContext(), getResources().getString(R.string.error),
							Toast.LENGTH_LONG).show();
				}
			}
		};

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				HttpClient cliente = new DefaultHttpClient();
				HttpGet get = new HttpGet();

				try {
					get.setURI(new URI(
							"http://tiestudios.com/api/Catalog/login_ws.php?id="
									+ id));
					HttpResponse respuesta = cliente.execute(get);
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(respuesta.getEntity()
									.getContent(), "UTF-8"));

					String json = reader.readLine();
					if (json != null) {
						JSONObject preArray = new JSONObject(json);
						esEmpleado = preArray.getString("empleado");
						handler.sendEmptyMessage(0);
					}
				} catch (NullPointerException e){
					e.printStackTrace();

				} catch (URISyntaxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();
	}

	//Guarda en SharedProperties el ultimo DNI logeado
	private void guardarID() {
		SharedPreferences settings = getSharedPreferences("ajustes",
				MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("dni", txtId.getText().toString());
		editor.commit();
	}

	//Compara el DNI introducido con el de SharedProperties
	private boolean compararID() {
		String id = txtId.getText().toString();
		SharedPreferences settings = getSharedPreferences("ajustes",
				MODE_PRIVATE);
		if (id.equalsIgnoreCase(settings.getString("dni", ""))) {
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.ok), Toast.LENGTH_LONG)
					.show();
			return true;
		}
		txtId.setText("");
		Toast.makeText(getApplicationContext(), getResources().getString(R.string.error), Toast.LENGTH_LONG)
				.show();
		return false;
	}

	//Comprueba que el dispositivo tiene conexion wi-fi o por datos
	public boolean networkAvailable() {
		Context context = getApplicationContext();
		ConnectivityManager connectMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectMgr != null) {
			NetworkInfo[] netInfo = connectMgr.getAllNetworkInfo();
			if (netInfo != null) {
				for (NetworkInfo net : netInfo) {
					if (net.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} else {
			Log.d("NETWORK", getResources().getString(R.string.error));
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}

}
